import sys
import os
from sgmllib import SGMLParser
import ctypeslib



scopeFuncDir = "../doc/scopeFunc/"
file_list = os.listdir(scopeFuncDir)

NISCOPE_ATTR = []
niScope_ = []
for file in file_list:
    if file.startswith("NISCOPE_ATTR"):NISCOPE_ATTR.append(file)
    elif file.startswith("niScope_"):niScope_.append(file)

tree_file = scopeFuncDir+"___left.htm"

os.environ["VXIPNPPATH"]


class get_tree_script_processor(SGMLParser):
    def reset(self):
        self.is_in_script = False
        SGMLParser.reset(self)
        
    def start_script(self,attrs):
        self.is_in_script = True
        
    def handle_comment(self,text):
        if self.is_in_script:
            self.script = text
            
    def end_script(self):
        self.is_in_script = False

class niScope_processor(SGMLParser):
    def reset(self):
        self.pieces = []
        SGMLParser.reset(self)
        
    def start_a(self,tag):
        print attrs
   
    def unknown_starttag(self, tag, attrs): 

        strattrs = "".join([' %s="%s"' % (key, value) for key, value in attrs])
        self.pieces.append("<%(tag)s%(strattrs)s>" % locals())

    def unknown_endtag(self, tag):          
        self.pieces.append("</%(tag)s>" % locals())

    def handle_charref(self, ref):          
        self.pieces.append("&#%(ref)s;" % locals())

    def handle_entityref(self, ref):        
        self.pieces.append("&%(ref)s" % locals())
        if htmlentitydefs.entitydefs.has_key(ref):
            self.pieces.append(";")


    def handle_comment(self, text):         
        self.pieces.append("<!--%(text)s-->" % locals())

    def handle_pi(self, text):              
        self.pieces.append("<?%(text)s>" % locals())

    def handle_decl(self, text):
        self.pieces.append("<!%(text)s>" % locals())

class NISCOPE_ATTR_processor(SGMLParser):
    def reset(self):
        self.pieces = []
        self.process_text = None
        self.td = 0
        self.description = ""
        self.process_tag_stack = []
        SGMLParser.reset(self)
        self.defined_values_index = -1
        self.span = ''
        
    def handle_data(self, text):          
        if self.process_text is not None:
            self.process_text(text)
            

    def unknown_starttag(self, tag, attrs):
        if tag == "p" and hasattr(self,"defined_values"):
            if len(self.defined_values) > 0 and len(self.defined_values[-1]) == 0:
                return
            self.defined_values.append([])
        if hasattr(self,"process_"+tag):
            self.process_tag_stack.append(self.process_text)
            self.process_text = getattr(self,"process_"+tag)

    def unknown_endtag(self, tag):
        if hasattr(self,"process_"+tag):
            fd = getattr(self,"process_"+tag)
            if len(self.process_tag_stack) > 0 :
                self.process_text = self.process_tag_stack.pop()
       
    def process_title(self,text):
       self.attr_name = text.strip("\n").strip()
            
    def process_td(self,data):
        if self.td == 0:
            self.dataType = data
        self.td += 1
        
    def process_h2(self,text):
        if text == "Description":
            self.process_p = self.set_description
            
    def set_description(self,text):
        self.description += text
           
    def process_h3(self,text):
        text = text.strip()
        if text == "Defined Values:" or text == "Defined Values":
            self.defined_values = []
            self.process_p = self.get_defined_values
    
    def get_defined_values(self,text):
        if text == "\n" or text == " ":
            return
        self.defined_values[-1].append(text)
    
#    def get_defined_values(self,text):
#        self.defined_values[self.span] = text  
            
#    def process_span(self,text):
#        self.span = text
 
        

def get_list_tree_from(script):
    list_tree = []
    script_list = script.rsplit("\n")
    for line in script_list:
        if not line.startswith("d.add("):
            continue
        line = line.replace("d.", "list_tree.")
        line = line.replace("(", "((")
        line = line.replace(")", "))")
        line = line.replace("add","append")
        line = line.replace(";","")
        eval(line)
    labels = {}
    branches = {}
    for item in list_tree:
        if "NISCOPE_ATTR_EXPORTED_SAMPLE_CLOCK_OUTPUT_TERM" == item[2]:
            continue
        labels[item[0]] = item[2]
        if branches.has_key(item[1]):
            branches[item[1]].append(item[0])
        else:
            branches[item[1]] = [item[0]] 
    return (branches,labels)

def printTree(level,tree,branches,labels):
    s = []
    for branch in tree:
        if branches.has_key(branch):
            className = labels[branch].replace(' ','_').replace('/','_')
            className = className.replace('(','').replace(')','')
            className = className.upper()
            s.append("\t"*(level+1)+"class "+className+":")
            s += printTree(level+2,branches[branch],branches,labels)
        else:
            s += process_attr(labels[branch],level)
            #print ("\t"*level+labels[branch])
    return s

def process_attr(attr,level):
    s = []
    file = open(scopeFuncDir+attr+".html","r")
    file_text = file.readlines()
    file.close()
    pro = NISCOPE_ATTR_processor()
    for line in file_text: pro.feed(line)
    if pro.attr_name[13:][0].isalpha():
        s.append("\t"*level+"class "+pro.attr_name[13:]+":")
    else:
        s.append("\t"*level+"class "+pro.attr_name+":")
    level += 1
    
    if hasattr(pro,"defined_values"):
    #    print ("\t"*level+"class "+pro.attr_name+":")
        for value in pro.defined_values:
            #value = value.rsplit(" ")[0]
            value = value[0]
            valueShort = value 
            if value.startswith("NISCOPE_VAL_") and value[12].isalpha():
                valueShort = value[12:]
            elif value.startswith("VI_") and value[3].isalpha():
                valueShort = value[3:]
            s.append("\t"*(level)+"def set"+valueShort+"(self,channel):")
            s.append("\t"*(level+1)+"self.setAttribute(self.vi,ViConstString(channel),ViAttr(%s),%s(%s))"%(pro.attr_name,pro.dataType,value))
    else:
        s.append("\t"*level+"def set"+"(self,channel,value):")
        s.append("\t"*(level+1)+"self.setAttribute(self.vi,ViConstString(channel),ViAttr(%s),%s(value))"%(pro.attr_name,pro.dataType))
    s.append("\t"*level+"def get"+"(self,channel):")
    s.append("\t"*(level+1)+"value = %s()"%pro.dataType)
    s.append("\t"*(level+1)+"self.getAttribute(self.vi,ViConstString(channel),ViAttr(%s),ctypes.byRef(value))"%(pro.attr_name))
    s.append("\t"*(level+1)+"return value.value")
    return s

    #print pro.defined_values
    pro.close()

#print "\n".join(process_attr("NISCOPE_ATTR_TRIGGER_TYPE",1))

#file = open(scopeFuncDir+"NISCOPE_ATTR_VERTICAL_RANGE.html","r")
#file_text = file.readlines()
#file.close()
#
#pro = NISCOPE_ATTR_processor()
#for line in file_text: pro.feed(line)
#print pro.attr_name
#print pro.dataType
#print pro.description
##print pro.defined_values
#pro.close()


file = open(tree_file,"r")
file_text = file.readlines()
file.close()

pro = get_tree_script_processor()
for line in file_text: pro.feed(line)
script = pro.script
pro.close()
(branches,labels) = get_list_tree_from(script)
s = printTree(0,branches[126],branches,labels)
print "\n".join(s)    
